package ae.pcfc.etks.online.itworx.ehs.web.messaging;

import java.util.Map;

import javax.jms.BytesMessage;
import javax.jms.Message;
import javax.jms.Session;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.listener.SessionAwareMessageListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import ae.pcfc.etks.online.itworx.ehs.web.compensation.CompensationManager;
import ae.pcfc.etks.online.itworx.ehs.web.constants.GlobalConstants;
import ae.pcfc.etks.online.itworx.ehs.web.model.Rollback;
import ae.pcfc.etks.online.itworx.ehs.web.web.controller.FNPInteraction;

@Component
public class RollbackJmsMessageListener implements SessionAwareMessageListener {

	
	private JmsTemplate template = null;
	private Logger log = LoggerFactory.getLogger(FNPInteraction.class);
	
	public void setTemplate(JmsTemplate template) {
		this.template = template;
	}

	private Map<String, CompensationManager> compensationManagers;

	public void setCompensationManagers(
			Map<String, CompensationManager> compensationManagers) {
		this.compensationManagers = compensationManagers;
	}

	/**
	 * Implementation of <code>MessageListener</code>.
	 */
	@Transactional
	public void onMessage(Message message, Session session) {
		try {

			if (message instanceof BytesMessage) {

				Rollback rollbackBean = (Rollback) template
						.getMessageConverter().fromMessage(message);

				if (null != rollbackBean.getFnpPaymentAdviceNumber()
						&& !rollbackBean.getFnpPaymentAdviceNumber().isEmpty()) {
					compensationManagers.get(
							GlobalConstants.FNP_COMPENSATION_MANAGER_KEY)
							.rollback(rollbackBean);
				}
				if (null != rollbackBean.getImsLogId()
						&& !rollbackBean.getImsLogId().isEmpty()) {
					compensationManagers.get(
							GlobalConstants.IMS_COMPENSATION_MANAGER_KEY)
							.rollback(rollbackBean.getImsLogId());
				}

			}
		} catch (Exception e) {
			log.error("RollbackJmsMessageListener.onMessage() - error happened while getting new message ("+message+")",e);
			throw new DataAccessResourceFailureException("Unexpected Failure",e); 
		}
	}
}
